﻿using Com.Pernix.Common.DataAccess;
using NHibernate;

namespace Com.Pernix.Component.Member
{
    public class UnitOfWork: IUnitOfWork
    {
        private readonly ISessionFactory _sessionFactory;
        private readonly ITransaction _currentTransaction;
        private ISession _currentSession;

        public UnitOfWork(ISessionFactory sessionFactory)
        {
            _sessionFactory = sessionFactory;
            _currentTransaction = CurrentSession.BeginTransaction();
        }

        public ISession CurrentSession
        {
            get { return _currentSession ?? (_currentSession = _sessionFactory.OpenSession()); }
        }

        public ITransaction BeginTransaction()
        {
            return _currentSession.BeginTransaction();
        }

        public void Commit()
        {
            if(_currentTransaction.IsActive)
            {
                _currentTransaction.Commit();
            }
        }

        public void Rollback()
        {
            if(_currentTransaction.IsActive)
            {
                _currentTransaction.Rollback();
            }
        }

        public void Dispose()
        {
            if(_currentSession == null)
            {
                return;
            }
            _currentSession.Dispose();
            _currentSession = null;
        }
    }
}
